package com.gxc.healthfood.controller;
import com.gxc.healthfood.common.ResponseResult;
import com.gxc.healthfood.entity.FoodNutrients;
import com.gxc.healthfood.entity.MealFoods;
import com.gxc.healthfood.entity.Meals;
import com.gxc.healthfood.service.DietPlansService;
import com.gxc.healthfood.service.FoodNutrientsService;
import com.gxc.healthfood.service.MealFoodsService;
import com.gxc.healthfood.service.MealsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器，处理用户相关的HTTP请求
 */

@RestController
@RequestMapping("/meals")

public class MealsController {
    @Autowired
    private MealsService mealsService;
    @Autowired
    private MealFoodsService mealFoodsService;
    @Autowired
    private FoodNutrientsService foodNutrientsService;
    /**

     * 创建餐次（设置餐次）

     * 为指定的饮食计划添加餐次，并分配卡路里

     */

    @PostMapping

    public ResponseResult<?> createMeal(@RequestBody Meals meal) {

        try {

// 参数验证

            if (meal == null) {

                return ResponseResult.error("餐次数据不能为空");

            }

            if (meal.getDietPlanId() == null) {

                return ResponseResult.error("饮食计划ID不能为空");

            }

//            if (meal.getMealType() == null || meal.getMealType().trim().isEmpty()) {
//
//                return ResponseResult.error("餐次类型不能为空");
//
//            }

            if (meal.getCalories() == null || meal.getCalories().compareTo(BigDecimal.ZERO) < 0) {

                return ResponseResult.error("卡路里必须大于等于0");

            }

// 设置创建时间

            meal.setCreatedAt(new Date());

// 保存餐次信息

            boolean saved = mealsService.save(meal);

            if (saved) {

//                logger.info("创建餐次成功，餐次ID：{}", meal.getId());

                return ResponseResult.success("创建餐次成功", meal);

            } else {

//                logger.error("创建餐次失败");

                return ResponseResult.error("创建餐次失败");

            }

        } catch (Exception e) {

//            logger.error("创建餐次异常", e);

            return ResponseResult.error("系统异常，请稍后重试");

        }

    }

    /**

     * 获取饮食计划的所有餐次

     */

    @GetMapping("/diet-plan/{dietPlanId}")

    public ResponseResult<?> getMealsByDietPlanId(@PathVariable Long dietPlanId) {

        try {

            if (dietPlanId == null) {

                return ResponseResult.error("饮食计划ID不能为空");

            }

// 构建查询条件

            Map<String, Object> conditions = new HashMap<>();

            conditions.put("diet_plan_id", dietPlanId);

// 查询餐次列表

            List<Meals> meals = mealsService.listByMap(conditions);

//            logger.info("查询饮食计划ID: {} 的餐次成功，共找到 {} 个餐次", dietPlanId, meals.size());

            return ResponseResult.success(meals);

        } catch (Exception e) {

//            logger.error("查询餐次异常", e);

            return ResponseResult.error("系统异常，请稍后重试");

        }

    }
    @RequestMapping("/meals")/**

     * 更新餐次信息

     */

    @PutMapping("/{id}")

    public ResponseResult<?> updateMeal(@PathVariable Long id, @RequestBody Meals meal) {

        try {

            if (id == null || meal == null) {

                return ResponseResult.error("参数不能为空");

            }

// 验证餐次是否存在

            Meals existingMeal = mealsService.getById(id);

            if (existingMeal == null) {

                return ResponseResult.error("餐次不存在");

            }

// 更新餐次信息

            meal.setId(id);

            boolean updated = mealsService.updateById(meal);

            if (updated) {

//                logger.info("更新餐次成功，餐次ID：{}", id);

                return ResponseResult.success("更新餐次成功");

            } else {

//                logger.error("更新餐次失败，餐次ID：{}", id);

                return ResponseResult.error("更新餐次失败");

            }

        } catch (Exception e) {

//            logger.error("更新餐次异常", e);

            return ResponseResult.error("系统异常，请稍后重试");

        }

    }

    /**

     * 删除餐次

     */

    @DeleteMapping("/{id}")

    public ResponseResult<?> deleteMeal(@PathVariable Long id) {

        try {

            if (id == null) {

                return ResponseResult.error("餐次ID不能为空");

            }

// 验证餐次是否存在

            Meals existingMeal = mealsService.getById(id);

            if (existingMeal == null) {

                return ResponseResult.error("餐次不存在");

            }

// 删除餐次（注意：实际项目中可能需要先删除关联的餐次食物）

            boolean deleted = mealsService.removeById(id);

            if (deleted) {

//                logger.info("删除餐次成功，餐次ID：{}", id);

                return ResponseResult.success("删除餐次成功");

            } else {

//                logger.error("删除餐次失败，餐次ID：{}", id);

                return ResponseResult.error("删除餐次失败");

            }

        } catch (Exception e) {

//            logger.error("删除餐次异常", e);

            return ResponseResult.error("系统异常，请稍后重试");

        }

    }

        /**

         * 为餐次添加食物

         * 根据食物ID和重量计算营养成分

         */

        @PostMapping("/{mealId}/foods")

        public ResponseResult<?> addFoodToMeal(@PathVariable Long mealId, @RequestBody MealFoods mealFood) {

            try {

                if (mealId == null || mealFood == null) {

                    return ResponseResult.error("参数不能为空");   }

// 验证餐次是否存在

                Meals meal = mealsService.getById(mealId);

                if (meal == null) {

                    return ResponseResult.error("餐次不存在");}

// 验证食物ID和数量

                if (mealFood.getFoodId() == null) {

                    return ResponseResult.error("食物ID不能为空");   }

                if (mealFood.getAmount() == null || mealFood.getAmount().compareTo(BigDecimal.ZERO) <= 0) {

                    return ResponseResult.error("食物数量必须大于0"); }

// 获取食物的营养成分

                FoodNutrients foodNutrients = foodNutrientsService.getByFoodId(mealFood.getFoodId());

                if (foodNutrients == null) {

                    return ResponseResult.error("未找到食物的营养成分数据");

                }

// 计算实际营养成分（根据食物数量计算）

                BigDecimal amount = mealFood.getAmount();

                BigDecimal calories = foodNutrients.getCalories().multiply(amount).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

                BigDecimal protein = foodNutrients.getProtein().multiply(amount).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

                BigDecimal fat = foodNutrients.getFat().multiply(amount).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

                BigDecimal carbohydrate = foodNutrients.getCarbohydrate().multiply(amount).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

// 设置餐次食物信息

                mealFood.setMealId(mealId);

                mealFood.setCalories(calories);

                mealFood.setProtein(protein);

                mealFood.setFat(fat);

                mealFood.setCarbohydrate(carbohydrate);

                mealFood.setCreatedAt(new Date());

// 保存餐次食物关系

                boolean saved = mealFoodsService.save(mealFood);

                if (saved) {

//                    logger.info("为餐次ID：{} 添加食物成功，食物ID：{}", mealId, mealFood.getFoodId());

                    return ResponseResult.success("添加食物成功", mealFood);

                } else {

//                    logger.error("为餐次添加食物失败");

                    return ResponseResult.error("添加食物失败");

                }

            } catch (Exception e) {

//                logger.error("为餐次添加食物异常", e);

                return ResponseResult.error("系统异常，请稍后重试");

            }

        }
//        获取餐次中的食物列表



        @GetMapping("/{mealId}/foods")

        public ResponseResult<?> getMealFoods(@PathVariable Long mealId) {

            try {

                if (mealId == null) {

                    return ResponseResult.error("餐次ID不能为空");

                }

// 构建查询条件

                Map<String, Object> conditions = new HashMap<>();

                conditions.put("meal_id", mealId);

// 查询餐次食物列表

                List<MealFoods> mealFoods = mealFoodsService.listByMap(conditions);

//                logger.info("查询餐次ID: {} 的食物成功，共找到 {} 个食物", mealId, mealFoods.size());

                return ResponseResult.success(mealFoods);

            } catch (Exception e) {

//                logger.error("查询餐次食物异常", e);

                return ResponseResult.error("系统异常，请稍后重试");

            }

        }
    /**

     * 从餐次中移除食物

     */

        @DeleteMapping("/{mealId}/foods/{foodId}")

        public ResponseResult<?> removeFoodFromMeal(@PathVariable Long mealId, @PathVariable Long foodId) {

        try {

            if (mealId == null || foodId == null) {

                return ResponseResult.error("参数不能为空");

            }

// 验证餐次是否存在

            Meals meal = mealsService.getById(mealId);

            if (meal == null) {

                return ResponseResult.error("餐次不存在");

            }

// 构建删除条件

            Map<String, Object> conditions = new HashMap<>();

            conditions.put("meal_id", mealId);

            conditions.put("food_id", foodId);

// 删除餐次食物关系

            boolean deleted = mealFoodsService.removeByMap(conditions);

            if (deleted) {

//                logger.info("从餐次ID：{} 移除食物ID：{} 成功", mealId, foodId);

                return ResponseResult.success("移除食物成功");

            } else {

//                logger.error("移除食物失败，可能该食物不存在于餐次中");

                return ResponseResult.error("移除食物失败，可能该食物不存在于餐次中");

            }

        } catch (Exception e) {

//            logger.error("移除餐次食物异常", e);

            return ResponseResult.error("系统异常，请稍后重试");
        }
        }
}